import { Component, OnInit, ViewChild } from '@angular/core';
import { STChange, STColumn, STComponent, STData, STPage, STRes } from '@delon/abc/st';
import { SFComponent, SFSchema, SFSelectWidgetSchema } from '@delon/form';
import { _HttpClient, SettingsService } from '@delon/theme';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-business-sale-statistics',
  templateUrl: './sale-statistics.component.html'
})
export class BusinessSaleStatisticsComponent implements OnInit {
  url = `api/statistics/shop_sale`;
  isAdmin = false;
  today = new Date();
  company_map = {};
  @ViewChild('sf', { static: false }) private sf!: SFComponent;
  searchSchema: SFSchema = {
    properties: {
      companyId: {
        type: 'string',
        title: '',
        readOnly: !this.isAdmin,
        ui: {
          widget: 'select',
          placeholder: '所属组织',
          asyncData: () =>
            this.loadCompany().pipe(
              map((value: any) => {
                return value;
              })
            ),
          change: i => {
            this.updateShop(i);
          }
        } as SFSelectWidgetSchema
      },
      shopId: {
        type: 'string',
        title: '',
        readOnly: !this.isAdmin,
        ui: {
          widget: 'select',
          placeholder: '店铺',
          showSearch: true
        } as SFSelectWidgetSchema
      }
    }
  };
  @ViewChild('st') private readonly st!: STComponent;
  columns: STColumn[] = [
    {
      title: '所属组织',
      index: 'company_name',
      className: 'text-center',
      format: (item: STData, col: STColumn, index: number) => {
        return this.company_map[item.company_id];
      }
    },
    { title: '店铺名称', index: 'fordeal_shop_name', className: 'text-center' },
    {
      title: { text: '昨日成交额', optionalHelp: '' },
      type: 'currency',
      index: 'shopSaleStatistics.yesterday',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopSaleStatistics.yesterday',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '前日成交额', optionalHelp: '' },
      type: 'currency',
      index: 'shopSaleStatistics.today_before_yesterday',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopSaleStatistics.today_before_yesterday',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '日均成交额', optionalHelp: '近7天订单销售额（订单收入）/ 7' },
      type: 'currency',
      index: 'shopSaleStatistics.avg_daily',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopSaleStatistics.avg_daily',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '订单销售额', optionalHelp: '近7天订单销售额（订单收入）' },
      index: 'shopSaleStatistics.grand_total',
      type: 'currency',
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopSaleStatistics.grand_total',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '较前日', optionalHelp: '日销售额涨跌（昨日/前日）' },
      // index: 'shopSaleStatistics.pct_change',
      format: (item: STData, col: STColumn, index: number) => {
        let num = parseFloat(item.shopSaleStatistics.pct_change) * 100;
        if (num > 0) {
          return `${num.toFixed(2)}%`;
        } else {
          return `${num.toFixed(2)}%`;
        }
      },
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopSaleStatistics.pct_change',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    },
    {
      title: { text: '售后罚金', optionalHelp: '' },
      type: 'currency',
      index: 'shopSaleStatistics.forfeit',
      format: (item: STData, col: STColumn, index: number) => {
        let num = parseFloat(item.shopSaleStatistics.forfeit);
        if (num > 0) {
          return `${num.toFixed(2)}%`;
        } else {
          return `${num.toFixed(2)}`;
        }
      },
      className: 'text-center',
      default: '-',
      sort: {
        key: 'ShopSaleStatistics.forfeit',
        reName: { ascend: 'asc', descend: 'desc' }
      }
    }
  ];

  res: STRes = {
    reName: {
      total: 'data.total',
      list: 'data.list'
    }
  };

  paginate: STPage = {
    showSize: true,
    pageSizes: [10, 20, 50, 100]
  };

  subPage: STPage = {
    front: false,
    show: false
  };

  shopList: any[] = [];
  loadCompany(): Observable<Array<{ label: any; value: any }>> {
    return this.http.get(`api/shop_map`).pipe(
      map((resp: any) => {
        let arr: Array<{ label: any; value: any }> = [];
        let list = resp.data['companies'];
        if (list && list.length) {
          list.forEach((element: { company_name: any; ID: any }) => {
            this.company_map[element.ID] = element.company_name;
            arr.push({ label: element.company_name, value: element.ID });
            this.shopList[element.ID] = [];
          });
        }
        let shops: any[] = resp.data['shops'];
        shops.forEach(shop => {
          this.shopList[shop['company_id']].push({ label: shop['fordeal_shop_name'], value: shop['shop_id'] });
        });
        return arr;
      })
    );
  }

  constructor(private http: _HttpClient, private settingService: SettingsService) {
    //console.log(this.settingService.user.ID);
    if (this.settingService.user.ID == 1) {
      this.isAdmin = true;
      let companyId = this.searchSchema?.properties?.companyId;
      if (companyId) {
        companyId.readOnly = false;
      }
      let shopId = this.searchSchema?.properties?.shopId;
      if (shopId) {
        shopId.readOnly = false;
      }
    }

    if (!this.isAdmin) {
      this.searchSchema = {
        properties: {}
      };
    }
  }

  ngOnInit = (): void => {};

  subTableData = [];
  @ViewChild('subst') private readonly subst!: STComponent;
  subTableColumns: STColumn[] = [
    {
      title: '图片',
      type: 'widget',
      width: 150,
      // index: 'sku_image_url',
      widget: { type: 'img', params: ({ record }) => ({ img: record.sku_image_url }) }
    },
    {
      title: { text: '商品ID', optionalHelp: '' },
      index: 'item_id',
      className: 'text-center',
      default: '-'
    },
    {
      title: { text: '商品名称', optionalHelp: '' },
      index: 'item_title',
      className: 'text-center',
      default: '-'
    },
    {
      title: { text: '销售额（订单收入）', optionalHelp: '' },
      index: 'grand_total',
      className: 'text-center',
      type: 'currency',
      default: '-'
    },
    {
      width: 300,
      title: { text: '趋势', optionalHelp: '7天销售额趋势' },
      type: 'widget',
      index: 'trend',
      className: 'text-center',
      widget: { type: 'g2-mini-area', params: ({ record }) => ({ visitData: record.trend }) }
    },
    {
      title: { text: '销售额', optionalHelp: '' },
      index: 'items_total',
      className: 'text-center',
      type: 'currency',
      default: '-'
    },
    {
      title: { text: '订单数', optionalHelp: '' },
      index: 'order_count',
      type: 'number',
      className: 'text-center',
      default: '-'
    },
    {
      title: { text: '客单价', optionalHelp: '' },
      type: 'currency',
      index: 'per_customer_price',
      className: 'text-center',
      default: '-'
    }
  ];
  subTableRes: STRes = {
    reName: {
      list: 'data'
    }
  };

  stChange($event: STChange<any>) {
    if ($event.type == 'expand' && $event.expand.expand) {
      let shopId = $event.expand.shop_id;
      this.http.get(`api/statistics/shop_item_sale`, { shopId: shopId }).subscribe(res => {
        this.subTableData = res.data;
      });
    }
  }

  updateShop(companyID: number): void {
    let property = this.sf.getProperty('/shopId');
    // @ts-ignore
    property.schema.enum = this.shopList[companyID];
    // @ts-ignore
    property.widget.reset('');
  }
}
